/**
 * 
 */
package response;

import java.util.Arrays;

import structures.Map;
import structures.Maze;

/**
 * Represents the map transmission format.
 * Header contains map dimensions, cell type counts.
 * Body contains map characters, left to right, up to down.
 * 
 * The Maze and Map structures are instantiated in the MapPacket constructor.
 * 
 * To be encapsulated within a CtfPacket.
 * 
 * @author lilywong
 *
 */
public class MapPacket {
	/* Instance Variables */
	MapHeader header;
	// array of characters that comprise the map
	char[] map;
	
	/* Constructor for client usage. 
	 * Reconstructs a MapPacket from the received server response. 
	 * Instantiates Maze and Map objects */
	public MapPacket( byte[] response ) {
		// reconstruct header
		byte[] headerInBytes = Arrays.copyOfRange(response, 0, MapHeader.LENGTH);
		header = new MapHeader( headerInBytes );
		// reconstruct body
		byte[] mapInBytes = Arrays.copyOfRange(response, MapHeader.LENGTH, response.length);
		map = new String( mapInBytes ).toCharArray();
		
		/************************ Maze and Map ******************************/
		// instantiate maze
		new Maze( header.getRows(), header.getCols(), header.getNumHome1(),
				header.getNumJail1(), header.getNumHome2(), header.getNumJail2(), 
				map );
		// instantiate a map object for the client
		new Map( header.getRows(), header.getCols(), map );
	}
	
	/* Accessors */
	public MapHeader getHeader() { return header; }
	public char[] getMap() { return map; }
	
	/**
	 * Convert packet into byte array in network byte order.
	 * @return byte array
	 */
	public byte[] toNetworkByteArray() {
		byte[] headerInBytes = header.toNetworkByteArray();
		byte[] body = new String( map ).getBytes();
		// concatenate header and body
		byte[] packetInBytes = new byte[ headerInBytes.length + body.length ];
		System.arraycopy(headerInBytes, 0, packetInBytes, 0, headerInBytes.length);
		System.arraycopy(body, 0, packetInBytes, headerInBytes.length, body.length);
		return packetInBytes ;
	}
}


